var cheerio = require("cheerio");
var async = require("async");
var utils = require('../dao/utils');
var Spider = require("./spider");

var insertDB = require("./insert.db");

var spider = new Spider('http://comic.kukudm.com/comictype/3_*PageReplace*.htm');
var host = "http://comic.kukudm.com";
spider.start(fun_urls,fun_pages,fun_detail);



function fun_urls(document){
    var $ = cheerio.load(document);

    var liArry = $('#comicmain dd'), urls = [];

    for (var i = 0; i < liArry.length; i++) {
        var item = liArry.eq(i);
        if (item.hasClass('ad_360_item')) {
            continue;
        }
        var url = host + item.find('a').eq(1).attr('href');
        
        urls.push(url);
    }

    return urls;
}


function fun_pages(document){
    var $ = cheerio.load(document);

    var href = $('table').eq(4).find("tr").eq(0).find("td").eq(1).find("table").eq(1).find("td").find("a").eq(-1).attr('href');

    var reg = /[1-9]\d./;
    
    array = reg.exec(href);
    return array?array[0]:108;//266
}

function fun_detail(url,document){

    var $ = cheerio.load(document);

    
    var contentTable = $('body').children('table').eq(4).children('tbody').children('tr').children('td').eq(1).find('table').eq(1).children('tbody').children('tr');

    var item = contentTable.eq(4).find('td').text().replace(/(^s*)|(s*$)/g, "");

    var title = contentTable.eq(0).find('td').text().replace(/(^s*)|(s*$)/g, "");

    var img = contentTable.eq(1).find('img').attr('src');

    title = title.slice(0, -2);



    if (item.length == 0) {
        return false;
    }

    var arry = item.split('|');

    // console.log(arry);

    var _auth = arry[0].split('：')[1];
    var time = arry[2].split('：')[1];

    // console.log(arry[1].split('：')[1]);

    var isFinish = arry[1].split('：')[1].replace(/(^s*)|(s*$)/g, "") == '连载' ? false : true;

    var chapter = [];


    var chaptersLis = $('#comiclistn dd');

    for (var i = 0; i < chaptersLis.length; i++) {
        var _cur = chaptersLis.eq(i);

        chapter.push({
            href: host + _cur.find('a').eq(0).attr('href').replace(/(^s*)|(s*$)/g, ""),
            chapter: _cur.find('a').eq(0).text().replace(/(^s*)|(s*$)/g, "")
        });
    }


    // var _sChapter = chapter.join(',');

    var data = {
        "title": title,
        "href": url,
        "img": img,
        "auth": _auth ? _auth.replace(/(^s*)|(s*$)/g, "") : null,
        "auth_href": null,
        "news": chapter.length>0? chapter[0]['chapter']:null,
        "news_href": chapter.length>0?chapter[0]['href']:null,
        "isFinish": isFinish,
        "updateTime": time ? time.replace(/(^s*)|(s*$)/g, "") : null,
        "type": null,
        "letter": utils.letter(title),
        "info": utils.trim($('#ComicInfo').text()),
        "domain": host,
        "isUpdate": true,
        "chapters": chapter,
    };

    insertDB(data);



}